package com.ruoyi.system.service.impl;

import com.ruoyi.system.domain.Medal;
import com.ruoyi.system.domain.UserMedal;
import com.ruoyi.system.mapper.MedalMapper;
import com.ruoyi.system.service.IMedalService;
import com.ruoyi.system.service.IUserMedalService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 勋章Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-25
 */
@Service
public class MedalServiceImpl implements IMedalService 
{
    @Autowired
    private MedalMapper medalMapper;
    @Autowired
    private IUserMedalService userMedalService; // 注入用户勋章服务（需新增）
    /**
     * 查询勋章
     * 
     * @param id 勋章主键
     * @return 勋章
     */
    @Override
    public Medal selectMedalById(Long id)
    {
        return medalMapper.selectMedalById(id);
    }

    /**
     * 查询勋章列表
     * 
     * @param medal 勋章
     * @return 勋章
     */
    @Override
    public List<Medal> selectMedalList(Medal medal)
    {
        return medalMapper.selectMedalList(medal);
    }

    /**
     * 新增勋章
     * 
     * @param medal 勋章
     * @return 结果
     */
    @Override
    public int insertMedal(Medal medal)
    {
        return medalMapper.insertMedal(medal);
    }

    /**
     * 修改勋章
     * 
     * @param medal 勋章
     * @return 结果
     */
    @Override
    public int updateMedal(Medal medal)
    {
        return medalMapper.updateMedal(medal);
    }

    /**
     * 批量删除勋章
     * 
     * @param ids 需要删除的勋章主键
     * @return 结果
     */
    @Override
    public int deleteMedalByIds(Long[] ids)
    {
        return medalMapper.deleteMedalByIds(ids);
    }

    /**
     * 删除勋章信息
     * 
     * @param id 勋章主键
     * @return 结果
     */
    @Override
    public int deleteMedalById(Long id)
    {
        return medalMapper.deleteMedalById(id);
    }
    @Override
    @Transactional // 保证事务一致性
    public void checkAndGrantMedals(Long userId, Long currentPoints) {
        // 查询所有未拥有且积分达标的勋章
        List<Medal> eligibleMedals = medalMapper.selectEligibleMedals(userId, currentPoints);

        for (Medal medal : eligibleMedals) {
            if (userMedalService.checkUserHasMedal(userId, medal.getId()) == 0) {
                UserMedal userMedal = new UserMedal();
                // 正确顺序：先设置属性，再插入
                userMedal.setUserId(userId);
                userMedal.setMedalId(medal.getId());
                userMedal.setMedalName(medal.getMedalName());
                userMedal.setDescription(medal.getDescription());
                userMedal.setCreatedTime(new Date()); // 设置获得时间
                userMedalService.insertUserMedal(userMedal); // 最后插入
            }
        }
    }

    @Override
    public Medal selectNextMedal(Integer currentPoints) {
        return medalMapper.selectNextMedal(currentPoints); // 调用Mapper层方法
    }
}
